package co.edu.uniandes.sd.interfaz;

import java.awt.Component;
import java.io.File;
import java.util.*;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;

public class FileTreeCellRenderer extends DefaultTreeCellRenderer
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Icon cache to speed the rendering.
     */
    private Map<String, Icon> iconCache = new HashMap<String, Icon>( );

    /**
     * Root name cache to speed the rendering.
     */
    private Map<File, String> rootNameCache = new HashMap<File, String>( );

    protected static FileSystemView fsv = FileSystemView.getFileSystemView( );

    public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus )
    {
        FileTreeNode ftn = ( FileTreeNode )value;
        File file = ftn.file;
        String filename = "";
        if( file != null )
        {
            if( ftn.isFileSystemRoot )
            {
                filename = this.rootNameCache.get( file );
                if( filename == null )
                {
                    filename = fsv.getSystemDisplayName( file );
                    this.rootNameCache.put( file, filename );
                }
            }
            else
            {
                filename = file.getName( );
            }
        }
        JLabel result = ( JLabel )super.getTreeCellRendererComponent( tree, filename, sel, expanded, leaf, row, hasFocus );
        if( file != null )
        {
            Icon icon = this.iconCache.get( filename );
            if( icon == null )
            {
                icon = fsv.getSystemIcon( file );
                this.iconCache.put( filename, icon );
            }
            result.setIcon( icon );
        }
        return result;
    }
}